package com.mp.approvalreq.util;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Email;
import com.mp.approvalreq.entity.common.Constants;
import com.plusmoney.mq.MQProducer;
import com.plusmoney.util.Utils;
import org.apache.rocketmq.client.exception.MQClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xq
 */
public class MQUtils {

    private static final Logger logger = LoggerFactory.getLogger(com.mp.checkin.util.MQUtils.class);

    /**
     * 发消息（重试三次）
     *
     * @param topic
     * @param tags
     * @param obj
     */
    public static void sendMessage(String topic, String tags, Object obj) {
        try {
            sentMessageWithRetry(topic, tags, null, obj, 3);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }

    }

    /**
     * 发消息（重试三次）
     *
     * @param topic
     * @param tags
     * @param key
     * @param obj
     */
    public static void sendMessage(String topic, String tags, String key, Object obj) {
        try {
            sentMessageWithRetry(topic, tags, key, obj, 3);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }

    }

    private static void sentMessageWithRetry(String topic, String tags, String key, Object obj, int retryTimes) throws Throwable {
        try {
            logger.info("topic:{},tags:{},key:{},retryTimes:{},msg:{}", topic, tags, key, retryTimes, JSONObject.toJSONString(obj));
            try {
                send(topic, tags, key, obj);
            } catch (Throwable e) {
                logger.error(e.getMessage(), e);
                if (retryTimes > 0) {
                    try {
                        Thread.sleep(100);
                        EmailUtils.sendMail("开始重试", JSONObject.toJSONString(obj));
                        sentMessageWithRetry(topic, tags, key, obj, --retryTimes);
                    } catch (Throwable e1) {
                        EmailUtils.sendMail("重试失败", JSONObject.toJSONString(obj));
                    }
                }
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            try {
                EmailUtils.sendErrorMail("初始化消费者失败", e.getMessage());
            } catch (Throwable throwable) {
                logger.error(throwable.getMessage(), throwable);
            }
            if (retryTimes > 0) {
                sentMessageWithRetry(topic, tags, key, obj, --retryTimes);
            }
        }
    }

    private static void send(String topic, String tags, String key, Object obj) throws Throwable {
        if (Utils.isNull(key)) {
            MQProducer.send(topic, tags, obj);
        } else {
            MQProducer.send(topic, tags, key, obj);
        }
    }
}
